#!/usr/bin/python3
import click 
import os
import platform
import logging
import sys
import tarfile
import requests as re

FC_VERSION = "v1.3.3"
logging.getLogger().setLevel(logging.DEBUG)


@click.group()
def cli():
    pass


@cli.command()
@click.option('--path', default=os.path.dirname(__file__), 
    help='Path to install firecracker binary to')
def fcinstall(path):
    """ Installs firecracker binary """
    ARCH = platform.uname().processor
    FC_DOWNLOAD_LINK = f"https://github.com/firecracker-microvm/firecracker/releases/download/{FC_VERSION}/firecracker-{FC_VERSION}-{ARCH}.tgz"
    resp = re.get(FC_DOWNLOAD_LINK)
    logging.debug("Link to get FC: " + FC_DOWNLOAD_LINK)
    open("firecracker.tgz", "wb").write(resp.content)
    tarfile.open("firecracker.tgz").extractall("./.fc")
    os.remove("firecracker.tgz")
    os.symlink(f"{os.path.abspath(path)}/.fc/release-{FC_VERSION}-{ARCH}/firecracker-{FC_VERSION}-{ARCH}", 
        ".fc/firecracker")


def system_check():
    """ Check if system is compatible with this script"""
    if platform.uname().system != "Linux":
        sys.exit("Compatible only with Linux")
    if not os.path.exists("/dev/kvm"):
        sys.exit("/dev/kvm not found")
    if not os.access("/dev/kvm", os.W_OK) or not os.access("/dev/kvm", os.W_OK):
        sys.exit("You should have permissions to read/write to /dev/kvm")



if __name__ == '__main__':
    system_check()
    cli()